import { tree } from '@/api/quality/reality/index'
import Moment from 'moment'
import Vue from 'vue'

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9
    ? '早上好，又是元气满满的一天呀'
    : hour <= 11
      ? '上午好，又是元气满满的一天呀'
      : hour <= 13
        ? '中午好，忘却烦躁，放眼今天，无限美好'
        : hour < 20
          ? '下午好，积攒更多快乐，享受美好人生'
          : '晚上好，音乐让人舒心，赞美让人甜心'
}

export function welcome() {
  const arr = ['休息一会儿吧']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 计算传入时间与当前时间的差值分钟，大于30分钟时返回原时间字符串
 * @param {String} timeStr
 */
export function getTimeGap(timeStr) {
  const nowTimeStamp = Moment().valueOf()
  const targetTimeStamp = Moment(timeStr).valueOf()
  const gapMinutes = parseInt((nowTimeStamp - targetTimeStamp) / 1000 / 60)
  return gapMinutes <= 30 ? `${gapMinutes}分钟前` : timeStr
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () { }
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = s => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

//提交时检查附件是否上传
export function isAttachment(that, auditStatus, list, msg = '') {
  if (auditStatus == 'SUBMITTED') {
    auditStatus = 1
  }
  if (msg == '') {
    msg = '请上传附件'
  }
  if (auditStatus == 1 && (list == undefined || list == null || list.length == 0)) {
    that.$message.warning(msg)
    return true
  } else {
    return false
  }
}
export const typeListApproval = [
  {
    value: '0',
    label: '待提交审批'
  },
  {
    value: '1',
    label: '审批中'
  },
  {
    value: '2',
    label: '审批通过'
  },
  {
    value: '3',
    label: '审批不通过'
  },
  {
    value: '5',
    label: '已作废'
  }
]
export const typeListApprova2 = [
  {
    value: '0',
    label: '待提交审批'
  },
  {
    value: '1',
    label: '审批中'
  },
  {
    value: '2',
    label: '审批通过'
  },
  {
    value: '3',
    label: '审批不通过'
  },
]

export const typeListApproval1 = [
  {
    value: 'DRAFT',
    label: '待提交审批'
  },
  {
    value: 'SUBMITTED',
    label: '审批中'
  },
  {
    value: 'PAST',
    label: '审批通过'
  },
  {
    value: 'REJECTED',
    label: '审批不通过'
  },

]
export const typeListApproval3 = [
  {
    value: 'DRAFT',
    label: '待提交'
  },
  {
    value: 'SUBMITTED',
    label: '已提交'
  }

]

/**
 * 通知父窗口,事件为'finish'
 * 目前用于待办事项页面刷新
 */
export function notifyParentWindow() {
  window.opener.postMessage('finish', window.location.origin)
}

/**
 * 判断业务详情中的组件是否需要显示
 * @param {Object} context 传入的上下文，引用时传入this即可
 */
export function checkVisibleInDetail(context) {
  try {
    // 移动端会在query上传入 clientMode=phone 参数，此时不需要显示部分组件（如返回、关闭按钮）
    const { clientMode } = context.$route.query
    return clientMode !== 'phone'
  } catch (e) {
    console.error(e)
    return true
  }
}

/**
 * 生成定时器处理函数(用于即时刷新的场景)
 * @param {Function} callback
 * @param {Number} delay
 *
 */
export function useTimer() {
  const fn = (callback, delay = 16.6) => {
    // requestAnimationFrame 没有的话则降级为setTimeout
    if (window.requestAnimationFrame) {
      window.requestAnimationFrame(callback)
    } else {
      window.setTimeout(callback, delay)
    }
  }
  const cancelFn = window.requestAnimationFrame ? window.cancelAnimationFrame : window.clearTimeout
  return [fn, cancelFn]
}

/**
 * 获取菜单图标
 * @param {string} code 菜单编码
 */
export function getMenuIcon(code) {
  // 如果图标不存在，就返回空
  try {
    return require(`../../src/assets/icons/${code}.png`)
  } catch (e) {
    // console.error(e)
    return ''
  }
}

/**
 * 获取自定义菜单的图标
 */
export function getCustomMenuIcon(code) {
  try {
    return require(`../../src/assets/indexPage/menuIcon/${code}.png`)
  } catch (e) {
    console.error(e)
    return ''
  }
}

/**
 * 从列表页打开审批页面
 */
export function handleAuditInList(val, general) {
  console.log(val, general,'aaaaaaaaaaaaaaaaaaaaaaaaa');
  //general 是否跳转通过审批页面，默认false
  if (!val.businessId) {
    this.$error({ content: '无有效业务ID，请刷新数据重试！' })
    return
  }
  // try {
  //   const userInfo = Vue.getAcloudProvider().getUserInfo()
  //   const posts = userInfo?.employee?.posts || []
  //   const target = posts.find(item => item.id === val.groupId)
  //   // 如果groupId指定的岗位在当前账号的岗位列表中，并且登录所选岗位与groupId不一致，那么就提示需要切换岗位才能审批（由于工会岗位和登录所选岗位是分开的，所以需要先判断groupId是否存在于当前账号的岗位列表）
  //   if (target && userInfo?.currentPost?.postId !== val.groupId) {
  //     this.$message.warning(`该审批信息为${target.name}岗位审批，请您切换岗位后审批`)
  //     return
  //   }
  // } catch {
  //   this.$message.warning('未查询到正确的审批岗位')
  //   return
  // }
  const query = {
    taskDefKey: val.taskDefKey,
    businessType: val.businessType,
    businessId: val.businessId,
    id: val.businessId,
    procInstId: val.procInstId,
    name: encodeURIComponent(val.taskName),
    processName: encodeURIComponent(val.processName),
    taskId: val.taskId,
    durationInMillis: val.durationInMillis, //滞留时间
    type: 'approve', // 部分详情页依赖这个参数做相关判断
    // 流程监控进入(区别审批按钮)
    isMonitoring: val.isMonitoring,
    // 流程主键(获取流程配置信息)
    processKey: val.processKey,
    // 流程监控类型,流程监控查看特殊跳转,流程监控时会传该参数否则不传(process:处理)
    monitoringType: val.monitoringType,
    // 区分业务已办查看处理信息
    resolveInfo: val.resolveInfo,
    //区分流程监控是否为查看 1为查看
    editModel:val.editModel,
    orgin: val.orgin // 来源
  }
  if (val.detailUrl) {
    query['detailUrl'] = encodeURIComponent(val.detailUrl)
  }
  if (general) {
    val.taskPcUrl = '/process/audit';
  }
  let routeData = this.$router.resolve({
    path: val.taskPcUrl,
    query
  })
  console.log(routeData,'2222')
  window.open(routeData.href, '_blank')
}

/**
 * 跳转到审批详情
 */
export function toAuditDetail(data) {
  console.log(data,'aaaaaaaaaaaaaaaaaaaaaaaaa');
  const constantRouterMap = require('@/config/router.config').constantRouterMap
  // const { detailUrl, businessId, businessType, procInstId } = data
  // 是否为单独的详情页面,是则打开新页面，否则跳转正常的详情页
  if (constantRouterMap.some(i => i.path === data.detailUrl)) {
    const routeData = this.$router.resolve({
      path: data.detailUrl,
      query: {
        // businessId: businessId,
        // businessType: businessType || '',
        // id: businessId,
        // type: 'approve'
        // 这里以前的已办事项查看审批有问题修改为待办事项的参数
        taskDefKey: data.taskDefKey,
        businessType: data.businessType,
        businessId: data.businessId,
        id: data.businessId,
        procInstId: data.procInstId,
        name: encodeURIComponent(data.taskName),
        processName: encodeURIComponent(data.processName),
        taskId: data.taskId,
        type: 'approve', // 部分详情页依赖这个参数做相关判断
        isView: true // 是否为查看
      }
    })
    console.log(data,'aaaaaaaaaaaaaaaaaaaaaaaaa');
    window.open(routeData.href, '_blank')
  } else {
    const routeData = this.$router.resolve({
      // 避免参数丢失
      path: data?.detailUrl?.split('?').length > 1 ? `/process/auditBusinessDetail?${data.detailUrl.split('?')[1]}` : '/process/auditBusinessDetail',
      query: {
        // businessId: businessId,
        // businessType: businessType || '',
        // detailUrl: detailUrl,
        // id: businessId,
        // type: 'approve'
        // 这里以前的已办事项查看审批有问题修改为待办事项的参数
        detailUrl: data.detailUrl,
        taskDefKey: data.taskDefKey,
        businessType: data.businessType,
        businessId: data.businessId,
        id: data.businessId,
        procInstId: data.procInstId,
        name: encodeURIComponent(data.taskName),
        processName: encodeURIComponent(data.processName),
        taskId: data.taskId,
        type: 'approve', // 部分详情页依赖这个参数做相关判断
        isView: true // 是否为查看
      }
    })
    console.log(data,'aaaaaaaaaaaaaaaaaaaaaaaaa');
    window.open(routeData.href, '_blank')
    // this.$router.push({
    //   path: detailUrl,
    //   query: {
    //     businessId: businessId,
    //     id: businessId,
    //     type: 'approve'
    //   }
    // })
  }
}

/**
 * 解析性别
 * @param {Number|String} val
 * @returns
 */
export function resolveSex(val) {
  const sexMap = {
    0: '女',
    1: '男'
  }
  return sexMap[val] || ''
}

/**
 * 生成随机字符串 + 时间戳作为唯一id
 */
export function randomString(len) {
  len = len || 32
  let timestamp = new Date().getTime()
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  let maxPos = $chars.length
  let randomStr = ''
  for (let i = 0; i < len; i++) {
    randomStr += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return randomStr + timestamp
}

/**
 * 设置checkbox列表的显示条数
 * params: {
 *   cacheList: array //页面缓存字段
 *   selectedRowKeys：arr // 选中的keys
 *   selectedRows： arr //选中的行
 *   prop: row-key // 列表唯一key
 * }
 * */

export function setTableListTopNum(cacheList, selectedRowKeys, selectedRows, prop) {
  selectedRows.forEach(item => {
    if (!cacheList.find((v) => v[prop] === item[prop])) {
      cacheList.push(item)
    }
  })
  const arr = []
  cacheList.forEach(item => {
    if (selectedRowKeys.find(v => v === item[prop])) {
      arr.push(item)
    }
  })
  return arr
}

// 平铺数组对象
export const generateList = (data, config = { childrenKey: 'children' }) => {
  if (!(data instanceof Array)) return []
  const list = []
  const fun = (current) => {
    current.forEach(item => {
      const { [config.childrenKey]: children, ...others } = item
      list.push(others)
      if (children && !!children.length) {
        fun(children)
      }
    })
  }
  fun(data)
  return list
}

// 深度查询树形结构
export const findNodeFromTree = (treeData, config = { key: 'id', childrenKey: 'children', value: '' }) => {
  const { key, value, childrenKey } = config
  let isGet = false;
  let retNode = null;
  function deepSearch(tree) {
    for (var i = 0; i < tree.length; i++) {
      if (tree[i][childrenKey || 'children'] && !!tree[i][childrenKey || 'children'].length) {
        deepSearch(tree[i][childrenKey || 'children'])
      }
      if (value === tree[i][key || 'id'] || isGet) {
        isGet || (retNode = tree[i])
        isGet = true
        break
      }
    }
  }
  deepSearch(treeData)
  return retNode
}

// 深度设置树结构，会改变原对象
export const setNodeInTree = (treeData, setValue = {}, config = { childrenKey: 'children' }) => {
  if (!Object.keys(setValue).length) return treeData
  const keys = Object.keys(setValue)
  const fun = (tree) => {
    tree.forEach(item => {
      keys.forEach(key => {
        item[key] = typeof setValue[key] === 'function' ? setValue[key](item) : setValue[key]
      })
      if (!!item[config.childrenKey] && !!item[config.childrenKey].length) {
        fun(item[config.childrenKey])
      }
    })
  }
  fun(treeData)
  return treeData
}

// 返回父级树形结构中某个节点父级的某个key的值
export const getParentKey = (tree, config = { key: 'id', value: '', childrenKey: 'children' }) => {
  const { key, value, childrenKey } = config
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node[childrenKey || 'children']) {
      if (node[childrenKey || 'children'].some(item => item[key] === value)) {
        parentKey = node[key];
      } else if (getParentKey(node[childrenKey || 'children'], config)) {
        parentKey = getParentKey(node[childrenKey || 'children'], config)
      }
    }
  }
  return parentKey
}

// 返回树形结构中当前节点上层节点集合，树形搜索时使用
export const getParentKeys = (tree, config = { key: 'id', value: '', childrenKey: 'children', parentKey: 'parentId' }) => {
  config = {
    key: 'id',
    childrenKey: 'children',
    parentKey: 'parentId',
    ...config,
  }
  const { key, value, childrenKey, parentKey } = config
  const parentValues = []
  const treeList = generateList(tree, { childrenKey })
  const fun = (currentValue) => {
    const node = treeList.find(item => item[key] === currentValue)
    if (node && node[parentKey]) {
      parentValues.push(node[parentKey])
      fun(node[parentKey])
    }
  }
  fun(value)
  return parentValues.filter(val => !!val)
}

// 获取浏览器参数
export const getUrlParam = (name) => {
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if(r!=null)
  return unescape(r[2]);
  return null;
}
// 数字转汉字
export const numberToString = (number) => {
  if (String(number).match(/\D/) || number.length >= 14) return;
  let zhArray = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']; // 数字对应中文
  let baseArray = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万']; //进位填充字符，第一位是 个位，可省略
  let string = String(number).split('').reverse().map((item, index) => { // 把数字切割成数组并倒序排列，然后进行遍历转成中文
    // 如果当前位为0，直接输出数字， 否则输出 数字 + 进位填充字符
    item = Number(item) == 0 ? zhArray[Number(item)] : zhArray[Number(item)] + baseArray[index];
    return item;
  }).reverse().join(''); // 倒叙回来数组，拼接成字符串
  string = string.replace(/^一十/, '十');  // 如果以 一十 开头，可省略一
  string = string.replace(/零+/, '零');  // 如果有多位相邻的零，只写一个即可
  return string;
}
// map根据value找key
export function findKeyByValue(target,toFind){
  let key = null
  target.forEach(function(value, k) {
    if (value === toFind) {
      key = k
    }
  })
  return key
}